package com.app.couponsharelife.ui.main.me
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.core.widget.NestedScrollView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.hwangjr.rxbus.thread.EventThread
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.TopBanner
import com.app.couponsharelife.data.bean.UserCenterBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.dialog.TYGImagDialog
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.me.about.AboutUsActivity
import com.app.couponsharelife.ui.main.me.bindalipay.BindAlipayActivity
import com.app.couponsharelife.ui.main.me.collect.CollectActivity
import com.app.couponsharelife.ui.main.me.customerservice.CustomerServiceActivity
import com.app.couponsharelife.ui.main.me.experiencemen.ExperienceMenActivity
import com.app.couponsharelife.ui.main.me.feedback.FeedbackActivity
import com.app.couponsharelife.ui.main.me.invite.ShareInvitePicActivity
import com.app.couponsharelife.ui.main.me.newteach.NewTeachActivity
import com.app.couponsharelife.ui.main.me.order.NewOrderActivity
import com.app.couponsharelife.ui.main.me.phonenum.BindPhoneNumActivity
import com.app.couponsharelife.ui.main.me.problem.ProblemActivity
import com.app.couponsharelife.ui.main.me.profit.ProfitActivity
import com.app.couponsharelife.ui.main.me.profit.record.NotProfitRecordActivity
import com.app.couponsharelife.ui.main.me.profit.record.ProfitRecordActivity
import com.app.couponsharelife.ui.main.me.setting.SettingActivity
import com.app.couponsharelife.ui.main.me.team.NewTeamActivity
import com.app.couponsharelife.ui.main.me.tribe.TicketTribeActivity
import com.app.couponsharelife.ui.main.me.withdrawal.WithdrawalActivity
import com.app.couponsharelife.utils.AppUtils
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_new_me.*
import java.util.HashMap
/**
 *Created by xct on 2019/4/25
 *Description:新个人中心页面
 */
class NewMeFragment:LazyFragment(),View.OnClickListener {
    private var yqCode=""
    private var aliPay=""
    private var mobile=""
    companion object {
        fun newInstance(): NewMeFragment {
            val fragment = NewMeFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_new_me

    override fun initViews() {
        newfrag_refreshLayout.setOnRefreshListener {
            newfrag_refreshLayout.isRefreshing=true
            getData(true)
        }
        newfrag_tvCopy.setOnClickListener(this)
        newfrag_ivSeting.setOnClickListener(this)
        newfrag_tvTX.setOnClickListener(this)
        newfrag_llDJSSY.setOnClickListener(this)
        newfrag_llYJSSY.setOnClickListener(this)
        newfrag_tvMeSY.setOnClickListener(this)
        newfrag_tvMeOrder.setOnClickListener(this)
        newfrag_tvMeTeam.setOnClickListener(this)
        newfrag_tvMeJR.setOnClickListener(this)
        newfrag_llYQHY.setOnClickListener(this)
        newfrag_llXSJC.setOnClickListener(this)
        newfrag_llWDSC.setOnClickListener(this)
        newfrag_llQGF.setOnClickListener(this)
        newfrag_llCJWT.setOnClickListener(this)
        newfrag_llWTFK.setOnClickListener(this)
        newfrag_llKFZX.setOnClickListener(this)
        newfrag_llGYWM.setOnClickListener(this)
        newfrag_scrollview.setOnScrollChangeListener(object :NestedScrollView.OnScrollChangeListener{
            override fun onScrollChange(v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
                if (scrollY>30){
                    newfrag_tvTitle.visibility=View.VISIBLE
                }else{
                    newfrag_tvTitle.visibility=View.INVISIBLE
                }
            }
        })
    }
    override fun onClick(v: View?) {
        when(v?.id){
            R.id.newfrag_tvCopy->{
                copyInviteCode(yqCode)
            }
            R.id.newfrag_ivSeting->{
                startActivity(Intent(context, SettingActivity::class.java))
            }
            R.id.newfrag_tvTX->{
                if (mobile.isEmpty()){
                    showToastMsg("请先绑定手机号")
                    val intent=Intent(context!!, BindPhoneNumActivity::class.java)
                    intent.putExtra("Type","Me")
                    startActivity(intent)
                }else{
                    if (aliPay.isNotEmpty()) {
                        val intent = Intent(activity!!, WithdrawalActivity::class.java)
                        //intent.putExtra("alipay", userCenterBean!!.alipay)
                        startActivity(intent)
                    } else {
                        showToastMsg("请先绑定支付宝账号")
                        val intent = Intent(context!!, BindAlipayActivity::class.java)
                        intent.putExtra("isWithdraw", true)
                        intent.putExtra("Mobile",mobile)
                        startActivity(intent)
                    }
                }
            }
            R.id.newfrag_llDJSSY->{  //待结算收益
                startActivity(Intent(context, NotProfitRecordActivity::class.java))
            }
            R.id.newfrag_llYJSSY->{  //累计结算收益
                startActivity(Intent(context, ProfitRecordActivity::class.java))
            }
            R.id.newfrag_tvMeSY->{  //我的收益
                startActivity(Intent(context, ProfitActivity::class.java))
            }
            R.id.newfrag_tvMeOrder->{  //我的订单
                startActivity(Intent(context, NewOrderActivity::class.java))
            }
            R.id.newfrag_tvMeTeam->{  //我的团队
                startActivity(Intent(context, NewTeamActivity::class.java))
            }
            R.id.newfrag_tvMeJR->{  //加入我们
                val intent = Intent(context, ExperienceMenActivity::class.java)
                intent.putExtra("Type", "1")
                startActivity(intent)
            }
            R.id.newfrag_llYQHY->{  //邀请好友
                startActivity(Intent(context, ShareInvitePicActivity::class.java))
            }
            R.id.newfrag_llXSJC->{  //新手教程
                startActivity(Intent(context, NewTeachActivity::class.java))
            }
            R.id.newfrag_llWDSC->{  //我的收藏
                startActivity(Intent(context, CollectActivity::class.java))
            }
            R.id.newfrag_llQGF->{   //券工坊
                startActivity(Intent(context, TicketTribeActivity::class.java))
            }
            R.id.newfrag_llCJWT->{ //常见问题
                startActivity(Intent(context, ProblemActivity::class.java))
            }
            R.id.newfrag_llWTFK->{  //问题反馈
                startActivity(Intent(context, FeedbackActivity::class.java))
            }
            R.id.newfrag_llKFZX->{  //客服中心
                startActivity(Intent(context, CustomerServiceActivity::class.java))
            }
            R.id.newfrag_llGYWM->{  //关于我们
                startActivity(Intent(context, AboutUsActivity::class.java))
            }
        }
    }
    @Subscribe(thread = EventThread.MAIN_THREAD, tags = [(Tag("mefrg_fraeshdata"))])
    fun refreshData(fresh: String) {
        lazyLoad()
    }
    override fun lazyLoad() {
        val type=AppUtils.getString("SXPay","")
        if ("true"==type){
            setTYGDialog("CEO")
        }
        getData(false)
    }
    private fun setData(userBean:UserCenterBean){
        val gradeID=(userBean.grade.id?:0).toString()
        mobile=userBean.mobile?:""
        AppUtils.setString(Contacts.USER_MOBILE, mobile)
        AppUtils.setString(Contacts.ADZONE_ID, userBean.relation_id?:"")
        AppUtils.setString(Contacts.USER_GRADE_ID, gradeID)
        AppUtils.setString(Contacts.INVITATION_CODE, userBean.requestcode?:"")
        AppUtils.setString(Contacts.COMMISSION_RATIO, userBean.commissionRatio?:"")
        AppUtils.setString(Contacts.ALIPAY_NUMBER, userBean.alipay?:"")
        newfrag_tvVIP.setOnClickListener {
            if ("4"==gradeID){
                setTYGDialog("CEO")
            }else if("5"==gradeID){
                setTYGDialog("Curriculum")
            }
        }
        val headUrl=if (userBean.headimgurl.startsWith("/")){
            Contacts.REMOTE_IMAGE_URL + userBean.headimgurl
        }else if(userBean.headimgurl.startsWith("//")){
            Contacts.TCP + userBean.headimgurl
        }else{
            userBean.headimgurl
        }
        Glide.with(context!!).asBitmap()
                .load(headUrl)
                .apply(RequestOptions().circleCrop().error(R.drawable.ic_tribe_boy_thumb))
                .into(newfrag_ivHead)
        newfrag_tvNickName.text=userBean.nickName?:"加载失败"
        newfrag_tvTitle.text=userBean.nickName?:"加载失败"
        newfrag_tvVIP.text=userBean.grade.name?:"vip"
        yqCode=userBean.requestcode
        aliPay=userBean.alipay?:""
        newfrag_tvYQCode.text="邀请码：$yqCode"
        val price=userBean.balance?:"0.00"
        val arrPrice=price.split(".")
        if (arrPrice.size>1){
            newfrag_tvYuED.text=arrPrice[0]
            val priceX=arrPrice[1]
            if (priceX.length>2) {
                newfrag_tvYuEX.text = ".${priceX.substring(0,2)}"
            }else{
                newfrag_tvYuEX.text =".$priceX"
            }
        }else{
            newfrag_tvYuED.text=arrPrice[0]
            newfrag_tvYuEX.text=".00"
        }
        val jsPrice=userBean.noSettleIncome?:"0.00"
        val arrJsPrice=jsPrice.split(".")
        if (arrJsPrice.size>1){
            newfrag_tvDJSSYPriceD.text=arrJsPrice[0]
            val priceX=arrJsPrice[1]
            if (priceX.length>2) {
                newfrag_tvDJSSYPriceX.text = ".${priceX.substring(0,2)}"
            }else{
                newfrag_tvDJSSYPriceX.text =".$priceX"
            }
        }else{
            newfrag_tvDJSSYPriceD.text=arrJsPrice[0]
            newfrag_tvDJSSYPriceX.text=".00"
        }
        val jsPrice1=userBean.alreadySettleIncome?:"0.00"
        val arrJsPrice1=jsPrice1.split(".")
        if (arrJsPrice1.size>1){
            newfrag_tvYJSSYPriceD.text=arrJsPrice1[0]
            val priceX=arrJsPrice1[1]
            if (priceX.length>2) {
                newfrag_tvYJSSYPriceX.text = ".${priceX.substring(0,2)}"
            }else{
                newfrag_tvYJSSYPriceX.text =".$priceX"
            }
        }else{
            newfrag_tvYJSSYPriceD.text=arrJsPrice1[0]
            newfrag_tvYJSSYPriceX.text=".00"
        }
        if (userBean.grade.name=="VIP"){
            newfrag_ivSvipBG.visibility=View.INVISIBLE
        }else{
            newfrag_ivSvipBG.visibility=View.VISIBLE
        }
        if (userBean.banners!=null&&userBean.banners.isNotEmpty()) {

            newfrag_mBanner.setImageLoader(GlideImageLoader())
                    .setImages(userBean.banners)
                    .setIndicatorGravity(BannerConfig.RIGHT)
                    .setOnBannerListener {
                        val banners = userBean.banners[it]
                        setBannerClic(userBean.banners[it])
                    }
                    .start()
        }
    }
    private fun setTYGDialog(type:String){
        TYGImagDialog(activity!!,R.style.DialogStyle,object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                copyInviteCode("https://mp.yiyepay.cn/jkpaymp")
                showToastMsg("复制成功！")
            }
        },type).show()
        AppUtils.setString("SXPay","")
    }
    private fun copyInviteCode(code: String) {
        //获取剪贴板管理器：
        val cm = context!!.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建普通字符型ClipData
        val mClipData = ClipData.newPlainText("Label", code)
        // 将ClipData内容放到系统剪贴板里。
        cm.primaryClip = mClipData
        showToastMsg("邀请码已复制")
    }
    private fun getData(isRefresh:Boolean){
        if (!isRefresh){
            showProgressDialog("加载中...")
        }
        val map= HashMap<String,String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        RetrofitWorker.retrofitWorker.userCenter(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<UserCenterBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<UserCenterBean>) {
                        if (!isRefresh){
                            dismissProgressDialog()
                        }
                        if (it.code==200&&it.data!=null){
                            if (isRefresh){
                                newfrag_refreshLayout.isRefreshing=false
                            }
                            setData(it.data!!)
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (!isRefresh){
                            dismissProgressDialog()
                        }
                        if (isRefresh){
                            newfrag_refreshLayout.isRefreshing=false
                        }
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    inner class GlideImageLoader: ImageLoader(){
        override fun displayImage(context: Context, path: Any, imageView: ImageView) {
            val pading= AppUtils.dip2px(context,12f)
            imageView.setPadding(pading,0,pading,0)
            val topBanner=path as TopBanner
            Glide.with(context).asBitmap()
                    .apply(RequestOptions().transforms(CenterCrop(), RoundedCorners( 15)).error(R.drawable.ic_app_place_holder2))
                    .load(Contacts.NEWREMOTE_IMAGE_URL +topBanner.imgPath)
                    .into(imageView)
        }
    }
}